package com.wavercaz.freeforum.controllers;

import com.wavercaz.freeforum.utils.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public ResponseResult upload(@RequestBody MultipartFile file) throws IOException {
        Map<String, String> res = new HashMap<>();
        String OriginalFilename = file.getOriginalFilename();
        String fileExtend = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        String finalFileName = UUID.randomUUID().toString()+fileExtend;
        String tragetFilePath =System.getProperty("user.dir")+"/static/images" + File.separator + finalFileName;
        File tragetFile = new File(tragetFilePath);
        if (!tragetFile.getParentFile().exists()) {
            tragetFile.getParentFile().mkdirs();
        }
        file.transferTo(tragetFile);
        res.put("imageUrl", "/images/"+finalFileName);
        return new ResponseResult(HttpStatus.OK.value(),res);
    }
}
